package md.frolov.bible.initializers;

import java.io.File;

import md.frolov.bible.Constants;
import md.frolov.bible.indexes.IX;
import md.frolov.bible.indexes.IXBible;
import md.frolov.bible.indexes.IndexManager;
import md.frolov.bible.model.Archive;
import md.frolov.bible.model.Book;
import md.frolov.bible.model.Chapter;
import md.frolov.bible.model.Module;

public class BibleParsingHandler extends ParsingHandler{
	Module lastModule;
	Book lastBook;
	File file;
	IX ix;
	
	public BibleParsingHandler(File f){
		file = f;
		ix = IndexManager.getInstance().getIndex(file);
		System.out.println("Index file: "+ix);
	}

	@Override
	public void error(){
		System.out.println("something went wrong");
	}

	@Override
	public void startElement(String tag, Attributes attributes, long offset){
		if(tag.equals(Constants.XML_VERSE_TAG)) return;
			
		if(tag.equals(Constants.XML_CHAPTER_TAG)){
			String id = attributes.get(Constants.XML_ATTRIBUTE_ID);
			Chapter c = new Chapter(id);
			lastBook.addChapter(c);
			c.setName(attributes.get(Constants.XML_ATTRIBUTE_NAME));
			
			ix.addOffset(id, offset);
			
			return;
		}
		
		if (tag.equals(Constants.XML_TAG_BOOK)){
			String id = attributes.get(Constants.XML_ATTRIBUTE_ID);
			String name = attributes.get(Constants.XML_ATTRIBUTE_NAME);
			lastBook = new Book(id);
			lastModule.addBook(lastBook);
			lastBook.setName(name);
			lastModule.addBookShortName(name, lastBook);
			return;
		}

		if (tag.equals(Constants.XML_TAG_SHORTNAME)){
			lastModule.addBookShortName(attributes.get(Constants.XML_ATTRIBUTE_NAME), lastBook);
			return;
		}
		
		if (tag.equals(Constants.XML_TAG_MODULE)){
			String id = attributes.get(Constants.XML_ATTRIBUTE_ID);
			lastModule = Archive.getInstance().getModuleByID(id);
			lastModule.setName(attributes.get(Constants.XML_ATTRIBUTE_NAME));
			lastModule.setShortName(attributes.get(Constants.XML_ATTRIBUTE_SHORT_NAME));
			lastModule.setCategory(attributes.get(Constants.XML_ATTRIBUTE_CATEGORY));
			lastModule.setLanguage(attributes.get(Constants.XML_ATTRIBUTE_LANGUAGE));
			lastModule.setFile(file);
			Archive.getInstance().addModuleStructure(lastModule);
			return;
		}
	}

	@Override
	public void endElement(String tag){
		if(tag.equals(Constants.XML_VERSE_TAG)) return;
		if(tag.equals(Constants.XML_CHAPTER_TAG)) return;
		if(tag.equals(Constants.XML_TAG_BOOK)){
			lastBook = null;
			return;
		}
		if(tag.equals(Constants.XML_TAG_MODULE)){
			lastModule = null;
			return;
		}
	}
	
}